package com.example.kotlin.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.ContentResolver
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.example.kotlin.R
import kotlinx.android.synthetic.main.activity_content_provide1.contact_listview

class ContentProvide1Activity : BaseActivity() {

    private val contactList=ArrayList<String>()
    private lateinit var arrayAdapter: ArrayAdapter<String>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_content_provide1)

        arrayAdapter=ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contactList)

        contact_listview.adapter=arrayAdapter

        if (ContextCompat.checkSelfPermission(this,Manifest.permission.READ_CONTACTS)
            !=PackageManager.PERMISSION_GRANTED){
            requestPermissions(arrayOf(Manifest.permission.READ_CONTACTS),1)
        }else{
            readContacts()
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when(requestCode){
            1->{
                if (grantResults.isNotEmpty() && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    readContacts()
                }else{
                    Toast.makeText(this,"拒绝了权限",Toast.LENGTH_SHORT).show()
                }
            }
        }


    }


    @SuppressLint("Range")
    private fun readContacts() {

        contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null,null,null,null)?.apply {
            while (moveToNext()){
                val displayName =
                    getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                val number =
                    getString(getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER))

                contactList.add("$displayName\n$number")
            }
            arrayAdapter.notifyDataSetChanged()
            close()
        }

    }
}